#include "dict.h"
#include "abb.h"
#include <stdlib.h>

struct sDict
{
	Abb dic;
	int tam;
};

Dict
dict_empty(void)
{
	Dict d;
	d = (Dict) malloc (sizeof(struct sDict));
	if (d!=NULL)
	{
		d->tam = 0;
		d->dic = abb_empty();
	}

return d;
}

void
dict_add(Dict d, Word w, Def f)
{
	Key k;
	Data dt;
	k = key_fromString(w);
	dt = data_fromString(f);
	abb_add(d->dic,k,dt);
	d->tam += 1;
	k = key_destroy(k); /*se clonan en mkTree */
	dt = data_destroy(dt);
}

Bool
dict_exists(Dict d, Word w)
{
	Bool b;
	Key k;
	k = key_fromString(w);
	b = abb_exists(d->dic,k);
	k = key_destroy(k);
return b;
}


Def
dict_search(Dict d, Word w)
{
	Def f;
	Key k;
	Data dt;
	if (dict_exists(d,w))
	{
		k = key_fromString(w);
		dt = abb_search(d->dic,k);
		f= data_toString(dt);
		k = key_destroy(k);
		dt = data_destroy(dt);
	}
	else
		f = NULL;

return f;
}
	
	
void
dict_del(Dict d, Word w)
{
	Key k;
	k = key_fromString(w);
	if (dict_exists(d,w))
	{
		abb_del(d->dic,k);
		d->tam -= 1;
	}
	k = key_destroy(k);
}

void
print_dict(Dict d)
{
	abb_print(d->dic);
}

int
dict_length(Dict d)
{
	int n;
	n = abb_length(d->dic);
return n;
}

Dict
dict_destroy(Dict d)
{
	if (d!=NULL)
	{	
		d->dic = abb_destroy(d->dic);
		free(d);
		d = NULL;
	}
return d;
}

Dict
dict_fromFile(char * nomfile)
{
	Dict d;
	d = dict_empty();
	d->dic = abb_destroy(d->dic); /*destruir porq la_fromFile pide memoria*/
	d->dic = abb_fromFile(nomfile);
	d->tam = abb_length(d->dic);
return d;
}

void
dict_toFile(char * nomfile, Dict d)
{
	abb_toFile(nomfile, d->dic);
}
